<template>
	<view>
		<!-- <view class="textArea_flex"> -->
		<block>
			<view class="updateBox" :style="'width: ' + width + ';height:' + height"
				v-for="(item, idx) in filePathsClone" :key="idx">
				<image :src="filePathsClone[idx]" class="updateBox_listImg" mode="aspectFit" @tap="imgYu"
					:id="filePathsClone[idx]" :data-text="idx" @longpress="deleteimg"></image>

				<image v-if="!disabled" src="/static/image/order/shanchu.png" class="updateBox_del" :data-text="idx"
					@tap="deleteimg"></image>
			</view>

			<view v-if="!disabled">
				<view class="updateBox" @tap="uploadimg" v-if="filePathsClone.length < length"
					:style="'width: ' + width + ';height:' + height">
					<image :src="addUrl" class="updateBox_add" :style="'width: ' + addWidth + ';height:' + addHeight">
					</image>
					<view class="updateBox_text" v-if="uploadText">{{ uploadText }}</view>
				</view>
			</view>
		</block>
	</view>
</template>

<script>
	const $URL = require('../../request/request');
	import {
		getBaseUrl
	} from '../../request/request';
	export default {
		data() {
			return {
				show: true,
				filePathsClone: []
			};
		},
		options: {
			virtualHost: true
		},
		props: {
			uploadText: {
				type: String,
				default: '上传图片'
			},
			// 上传图片数量
			length: {
				type: [Number, String],
				default: 1
			},
			isStatus: {
				type: Boolean,
				default: false
			},
			width: {
				type: [String, Number],
				default: '140rpx'
			},
			height: {
				type: [String, Number],
				default: '140rpx'
			},
			addUrl: {
				type: String,
				default: '/static/image/shopDetail/add.png'
			},
			addWidth: {
				type: [String, Number],
				default: '44.84rpx'
			},
			addHeight: {
				type: [String, Number],
				default: '44.84rpx'
			},
			disabled: {
				type: Boolean,
				default: false
			},
			filePaths: {
				type: Array,
				default: () => []
			}
		},
		// observers: {
		//   filePaths: function (val) {
		//     this.triggerEvent('onValue', val)
		//   }
		// },
		created() {
			// console.log(this.data.filePaths)
		},
		methods: {
			//传图片
			uploadimg: function() {
				if (this.disabled) {
					return;
				}

				let len = 0;
				var that = this;
				var filePaths2 = that.filePaths || [];
				var show2 = that.show;
				const {
					length
				} = that;
				console.log('length', length);

				if (filePaths2 != null) {
					len = filePaths2.length;
				}

				var that = this;
				let token = uni.getStorageSync('token');
				uni.chooseImage({
					count: length - len,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],

					success(res) {
						uni.showToast({
							title: '正在上传...',
							icon: 'loading',
							mask: true,
							duration: 1000
						});

						for (var i = 0; i < res.tempFilePaths.length; i++) {
							that.apiUpload(res.tempFilePaths[i]).then(iamge => {
								filePaths2.push(iamge);
								that.filePathsClone = filePaths2;
								that.show = filePaths2.length >= length ? false : true;
								that.$emit('onValue', {
									detail: that.filePaths
								});
							});
						}
					}
				});
			},
			//图片放大事件
			imgYu: function(event) {
				var that = this;
				var src = event.currentTarget.id; //获取当前图
				//图片预览

				uni.previewImage({
					current: src,
					// 当前显示图片的http链接
					urls: that.filePaths,
					// 需要预览的图片http链接列表
					success: function(info) {
						// console.info(info)
					},
					fail: function(errInfo) {
						// console.info(errInfo)
					}
				});
			},

			//删除图片
			deleteimg(e) {
				if (this.disabled) {
					return;
				}

				var that = this;
				var show2 = that.show;
				var id = e.currentTarget.dataset.text;
				var arr = that.filePaths;
				const {
					length
				} = that;
				uni.showModal({
					//使用模态框提示用户进行操作
					title: '警告',
					content: '你将删除此图片！',
					success: res => {
						if (res.confirm) {
							//判断用户是否点击了确定
							arr.splice(id, 1);

							if (arr.length > length) {
								show2 = false;
							} else {
								show2 = true;
							}

							that.setData({
								filePathsClone: arr,
								show: show2
							});
							this.$emit('onValue', {
								detail: that.filePaths
							});
						} else if (res.cancel) {
							return false;
						}
					}
				});
			},

			apiUpload(filePath) {
				let that = this
				let urlPath = getBaseUrl() + '/system/web/oss/upload'
				let fileName = filePath.substr(filePath.lastIndexOf('/') + 1);
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: urlPath,
						filePath: filePath,
						name: 'file',
						header: {
							// "Content-Type": "multipart/form-data",
							"Authorization": 'Bearer ' + localStorage.getItem("tokenValue"),
						},
						// formData: {
						// 	"fileName": fileName,
						// 	"file": filePath,
						// },
						success: function(res) {
							console.log('res数据', res)
							uni.hideLoading();
							let result = JSON.parse(res.data)
							let data = res.data ? JSON.parse(res.data) : {};
							console.log('data', data)
							if (data.code == 200) {
								resolve('https://boyubasketball.oss-cn-shanghai.aliyuncs.com/' + data
									.msg)
							} else {
								reject()
								uni.showToast({
									title: data.msg,
									icon: 'none'
								})
							}
						},
						fail: function(err) {
							reject()
							uni.hideLoading();
							uni.showToast({
								title: '上传图片失败',
								icon: 'none'
							})
						}
					})
				});
				// const COS = require('@/utils/cos-wx-sdk-v5.min.js')
				// const cos = new COS({
				// 	SimpleUploadMethod: 'putObject',
				// 	AppId: '1258084849',
				// 	SecretId: 'AKIDtingfUXZqwrfPxLeqrhGQK4c0d199jeK',
				// 	SecretKey: 'cyaw1YoqeBShiSu51jALZhYtW6RVIyRd'
				// })
				// return new Promise((resolve, reject) => {
				// 	let nowDate = new Date()
				// 	let date = {
				// 		year: nowDate.getFullYear(),
				// 		month: nowDate.getMonth() + 1,
				// 		date: nowDate.getDate()
				// 	}
				// 	const systemTime = `${date.year}-${date.month}-${date.date}`
				// 	let fileName = filePath.substr(filePath.lastIndexOf('/') + 1);
				// 	cos.postObject({
				// 			Bucket: 'smhs', // 存储桶
				// 			Region: 'ap-nanjing', // 地域
				// 			Key: 'smhswbjd/upload/' + systemTime + '/' + fileName,
				// 			FilePath: filePath,
				// 		},
				// 		function(err, data) {
				// 			resolve('http://' + data.Location)
				// 		})
				// });
			}
		},
		watch: {
			filePaths: {
				handler: function(newVal, oldVal) {
					this.filePathsClone = newVal;
				},

				immediate: true,
				deep: true
			}
		}
	};
</script>
<style>
	@import './uploadImg.css';
</style>